package com.sxygsj.baselibrary.network

import UploadService
import okhttp3.MultipartBody
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.await
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

/**
 * @Author LD
 * @Time 2021/3/5 9:35
 * @Describe 上传文件
 * @Modify
 */
object UploadWork {

    /**
     * 上传文件
     */
    private val uploadService =
        ServiceCreator.create(UploadService::class.java)

    /**
     * 上传单个文件
     */
    suspend fun uploadFile(url:String,multipartBody: MultipartBody.Part)= uploadService.uploadFile(url,multipartBody).await()



    /**
     * 上传多文件
     */
    suspend fun uploadFiles(url: String,list: List<MultipartBody.Part>) = uploadService.uploadFiles(url,list).await()
    /**
     * 简化回调的操作
     */
    private suspend fun <T> Call<T>.await(): T {
        return suspendCoroutine { continuation ->
            enqueue(object : Callback<T> {
                override fun onResponse(call: Call<T>, response: Response<T>) {
                    val body = response.body()
                    if (body != null) continuation.resume(body)
                    else continuation.resumeWithException(RuntimeException("资源文件不存在"))
                }

                override fun onFailure(call: Call<T>, t: Throwable) {
                    continuation.resumeWithException(t)
                }
            })
        }
    }
}